const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { HashedModuleIdsPlugin } = require('webpack');
const CompressionWebpackPlugin = require('compression-webpack-plugin'); // 开启压缩
const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); // 去掉注释
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackTagsPlugin = require('html-webpack-tags-plugin');
function resolve(dir) {
	return path.join(__dirname, dir);
}
const isProduction = process.env.NODE_ENV === 'production';

module.exports = {
	lintOnSave: true, // 保存时检查
	outputDir: 'dist', // 输出文件目录
	assetsDir: 'static', // 放置生成的静态资源 (js、css、img、fonts) 的目录
	productionSourceMap: false, // 如果你不需要生产环境的 source map，可以将其设置为 false 以加速生产环境构建
	devServer: {
		port: 8080,
		open: true,
		hot: true,
		overlay: {
			warnings: false,
			errors: true,
		},
		host: '0.0.0.0',
		disableHostCheck: true,
		// 代理示例
		proxy: {
			'/baiduApi': {
				target: 'http://api.map.baidu.com',
				ws: true,
				changeOrigin: true,
				pathRewrite: {
					'^/baiduApi': '/reverse_geocoding/v3/', // 代理的路径
				},
			},
		},
	},
	configureWebpack: config => {
		config.name = 'vue-cesium-template';
		config.resolve.alias = {
			'@': resolve('src'),
			V: resolve('src/views'),
			C: resolve('src/components'),
			U: resolve('src/utils'),
			E: resolve('src/earth'),
		};
		config.entry = isProduction
			? {
					app: resolve('./src/main.js'),
			  }
			: {
					Cesium: resolve('./ThirdParty/CesiumSource.js'),
					app: resolve('./src/main.js'),
			  };
		config.module.unknownContextCritical = false;
		const plugins = [];
		plugins.push(
			new webpack.DefinePlugin({
				CESIUM_BASE_URL: JSON.stringify('./Cesium/'),
			}),
			new CopyWebpackPlugin([
				{
					from: './node_modules/cesium/Build/Cesium',
					to: 'Cesium',
				},
			]),
			new HtmlWebpackPlugin({
				title: 'cesiumtemplate',
				filename: './index.html',
				template: './public/index.html',
			}),
			new HtmlWebpackTagsPlugin({
				append: false,
				links: './Cesium/Widgets/widgets.css',
			})
		);

		if (isProduction) {
			plugins.push(
				new HtmlWebpackTagsPlugin({
					append: false,
					scripts: 'Cesium/Cesium.js',
				}),
				//服务器也要相应开启gzip
				new CompressionWebpackPlugin({
					algorithm: 'gzip',
					test: /\.(js|css)$/, // 匹配文件名
					threshold: 10000, // 对超过10k的数据压缩
					deleteOriginalAssets: false, // 不删除源文件
					minRatio: 0.8, // 压缩比
				})
			);

			// 用于根据模块的相对路径生成 hash 作为模块 id, 一般用于生产环境
			plugins.push(new HashedModuleIdsPlugin());

			// 开启分离js
			config.optimization = {
				runtimeChunk: 'single',
				minimizer: [
					new UglifyJsPlugin({
						uglifyOptions: {
							warnings: false,
							compress: {
								drop_debugger: true,
								drop_console: true,
								pure_funcs: ['console.log'],
							},
							output: {
								comments: false,
							},
						},
						sourceMap: false,
						parallel: true,
					}),
				],
				splitChunks: {
					chunks: 'all',
					maxInitialRequests: Infinity,
					minSize: 1000 * 60,
					cacheGroups: {
						vendor: {
							test: /[\\/]node_modules[\\/]/,
							name(module) {
								// 排除node_modules 然后吧 @ 替换为空 ,考虑到服务器的兼容
								const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
								return `npm.${packageName.replace('@', '')}`;
							},
						},
					},
				},
			};

			// 取消webpack警告的性能提示
			config.performance = {
				hints: 'warning',
				// 入口起点的最大体积
				maxEntrypointSize: 1000 * 500,
				// 生成文件的最大体积
				maxAssetSize: 1000 * 1000,
				// 只给出 js 文件的性能提示
				assetFilter: function (assetFilename) {
					return assetFilename.endsWith('.js');
				},
			};
		} else {
			// 开发环境下配置source map，方便调试代码
			config.devtool = 'source-map';
		}
		return { plugins };
	},

	chainWebpack: config => {
		// 全局引入scss/sass文件
		// const oneOfsMap = config.module.rule('scss').oneOfs.store;
		// oneOfsMap.forEach(item => {
		//     item.use('sass-resources-loader')
		//         .loader('sass-resources-loader')
		//         .options({
		//             // Provide path to the file with resources
		//             // 要公用的scss的路径
		//             resources: ['./src/styles/varibles.scss'],
		//         })
		//         .end();
		// });
		// 压缩图片
		config.module
			.rule('images')
			.test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
			.use('image-webpack-loader')
			.loader('image-webpack-loader')
			.options({ bypassOnDebug: true });
		// webpack 会默认给commonChunk打进chunk-vendors，所以需要对webpack的配置进行delete
		config.optimization.delete('splitChunks');
	},
};
